package com.commerce.product.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.commerce.common.utils.PageResult;
import com.commerce.common.utils.Result;
import com.commerce.common.entity.Category;
import com.commerce.product.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/categories")
@CrossOrigin
public class CategoryController {
    private static final Logger log = LoggerFactory.getLogger(CategoryController.class);
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String CATEGORY_CACHE_PREFIX = "category:";

    /**
     * 获取所有分类
     */
    @GetMapping
    public Result<PageResult<Category>> getAllCategories(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResult<Category> pageResult = categoryService.getPageList(page + 1, size);
        return Result.success(pageResult);
    }

    /**
     * 分页获取分类
     */
    @GetMapping("/page")
    public Result<PageResult<Category>> getPageList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageResult<Category> pageResult = categoryService.getPageList(page, size);
        return Result.success(pageResult);
    }

    /**
     * 根据ID获取分类
     */
    @GetMapping("/{id}")
    public Result<Category> getCategoryById(@PathVariable Long id) {
        Category category = categoryService.getCategoryById(id);
        return Result.success(category);
    }

    /**
     * 添加分类
     */
    @PostMapping
    public Result<Boolean> addCategory(@RequestBody Category category) {
        boolean success = categoryService.addCategory(category);
        return Result.success(success);
    }

    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        category.setId(id);
        boolean success = categoryService.updateCategory(category);
        return Result.success(success);
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCategory(@PathVariable Long id) {
        boolean success = categoryService.deleteCategory(id);
        return Result.success(success);
    }
    
    /**
     * 清除所有分类相关缓存
     */
    private void clearAllCategoryCaches() {
        try {
            log.info("Controller层强制清除所有分类相关缓存");
            
            // 1. 清除所有以 category: 开头的缓存
            Set<String> allCategoryKeys = redisTemplate.keys(CATEGORY_CACHE_PREFIX + "*");
            if (allCategoryKeys != null && !allCategoryKeys.isEmpty()) {
                Long deletedCount = redisTemplate.delete(allCategoryKeys);
                log.info("清除所有分类相关缓存: {} 个键, 成功删除: {} 个", allCategoryKeys.size(), deletedCount);
                
                // 打印被删除的键，方便调试
                for (String key : allCategoryKeys) {
                    log.info("Controller删除缓存键: {}", key);
                }
            } else {
                log.info("未找到分类相关的缓存键");
            }
        } catch (Exception e) {
            log.error("Controller清除缓存失败: {}", e.getMessage(), e);
        }
    }
} 